package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.LoginLog;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service(version = "1.0.0")
public class LoginLogApiIml implements LoginLogApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean save(LoginLog LoginLog) {

        if (ObjectUtil.isEmpty(LoginLog.getLogTime())) {
            return false;
        }
        mongoTemplate.save(LoginLog);
        return true;
    }


    @Override
    public PageInfo<LoginLog> queryLoginlog(Integer page, Integer pageSize, String sortProp, String sortOrder, String userId) {
        PageInfo<LoginLog> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);


        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by("ascending".equals(sortOrder) ? Sort.Order.asc(sortProp) : Sort.Order.desc(sortProp)));
        Query query = Query.query(Criteria.where("userId").is(Convert.toLong(userId))).with(pageRequest);
        List<LoginLog> loginLogs = mongoTemplate.find(query, LoginLog.class);

        pageInfo.setRecords(loginLogs);

        return pageInfo;
    }

    /**
     * 根据userId查询日志，获取最新的日志
     * @param userId
     * @return
     */
    @Override
    public LoginLog getLoginLogById(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("logTime")));
        ArrayList<LoginLog> loginLogs = (ArrayList<LoginLog>) mongoTemplate.find(query, LoginLog.class);
        if (loginLogs.size() <= 0) {
            return null;
        }
        return loginLogs.get(0);
    }

    @Override
    public Long queryLoginlogCount(String userId) {
        long count = 0;
        try {
            Query query = Query.query(Criteria.where("userId").is(Convert.toLong(userId)));
            count = mongoTemplate.count(query, LoginLog.class);
        } catch (Exception e) {
            log.error("抱歉,查询错误", e);
        }
        return count;

    }
}
